package com.controller;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.grapecity.documents.excel.E;
import com.mypg.News;
import com.mypg.NewsHelper;
import com.mypg.Question;
import com.service.QuestionService;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.apache.commons.fileupload.util.Streams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RequestMapping("/question")
@Controller
public class QuestionController {

    @Autowired
    QuestionService questionService;

    @RequestMapping("/question_table_select.do")
    @ResponseBody
    public String doQuestion_table_select(String question_class,String question_chapter,String question_ori,
                                      int page, int limit) throws ParseException, JsonProcessingException {
        int start_row=(page-1)*limit;
        int page_nums=limit;
        HashMap<String,Object> map=new HashMap<>();
        map.put("code",0);
        map.put("msg","");
        map.put("count",questionService.selectQuestion_count_For_question_table_jsp(question_class,question_chapter,question_ori));
        List<Question> questionList=questionService.selectQuestionFor_question_table_jsp(question_class,question_chapter,question_ori,start_row,page_nums);
        map.put("data", questionList);
        ObjectMapper mapper=new ObjectMapper();
        String map_json_str=mapper.writeValueAsString(map);
        return map_json_str;
    }

    @RequestMapping("/question_table_delete_one.do")
    @ResponseBody
    public void doQuestion_table_delete_one(int question_id, HttpSession session){
        String path= (String) session.getAttribute("img_save_path");
        path+="/question_img/";
        Question question=questionService.selectQuestionByQuestion_id(question_id);
        File file=new File(path+question.getQuestion_img());
        file.delete();
        questionService.deleteQuestionByQuestion_id(question_id);
    }

    @RequestMapping("/question_table_delete_many.do")
    @ResponseBody
    public int doQuestion_table_delete_many(String[] question_id_array,HttpSession session){
        question_id_array[0]=question_id_array[0].replace("[","");
        question_id_array[question_id_array.length-1]=question_id_array[question_id_array.length-1].replace("]","");
        String path= (String) session.getAttribute("img_save_path");
        path+="/question_img/";
        for(int i=0;i<question_id_array.length;i++){
            Question question=questionService.selectQuestionByQuestion_id(Integer.parseInt(question_id_array[i]));
            File file=new File(path+question.getQuestion_img());
            file.delete();
            questionService.deleteQuestionByQuestion_id(Integer.parseInt(question_id_array[i]));
        }
        return 0;
    }

    @RequestMapping("/question_table_add_with_file.do")
    @ResponseBody
    public Map<String,Object> doQuestion_table_add_with_file(String question_content, String question_option,
                                                         String question_class, String question_chapter,String question_ori,String question_answer,
                                                         @RequestParam(value="file_content",required = false) MultipartFile file_content,
                                                         @RequestParam(value="file_option",required = false) MultipartFile file_option,
                                                         @RequestParam(value="file_img",required = false) MultipartFile file_img,
                                                         @RequestParam(value="file_video",required = false) MultipartFile file_video,
                                                         HttpSession session){
        News news=new News();
        String content_to_upload="";
        String option_to_upload="";
        String img_to_upload="";
        String video_to_upload="";

        if(file_content==null){
            content_to_upload=question_content;
        }else{
            if(!file_content.isEmpty()){
                try {
                    InputStream in = file_content.getInputStream();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
                    int a = 0;
                    while((a = bufferedReader.read())!=-1){
                        char ch=(char)a;
                        content_to_upload+=ch;
                    }
                    in.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

        if(file_option==null){
            option_to_upload=question_option;
        }else{
            if(!file_option.isEmpty()){
                try {
                    InputStream in = file_option.getInputStream();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
                    int a = 0;
                    while((a = bufferedReader.read())!=-1){
                        char ch=(char)a;
                        option_to_upload+=ch;
                    }
                    in.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

        if(file_img==null){
            img_to_upload="";
        }else{
            img_to_upload= UUID.randomUUID()+"_with_"+file_img.getOriginalFilename();
            String path= (String) session.getAttribute("img_save_path");
            path+="/question_img/";
            if(!file_img.isEmpty()){
                try {
                    File uploadFile=new File(path+img_to_upload);
                    Streams.copy(file_img.getInputStream(),new FileOutputStream(uploadFile.getAbsolutePath()),true);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        if(file_video==null){
            video_to_upload="";
        }else{
            video_to_upload= UUID.randomUUID()+"_with_"+file_video.getOriginalFilename();
            String path= (String) session.getAttribute("img_save_path");
            path+="/question_img/";
            if(!file_video.isEmpty()){
                try {
                    File uploadFile=new File(path+video_to_upload);
                    Streams.copy(file_video.getInputStream(),new FileOutputStream(uploadFile.getAbsolutePath()),true);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

        Question question=new Question();
        question.setQuestion_answer(question_answer);
        question.setQuestion_class(question_class);
        question.setQuestion_content(question_content);
        question.setQuestion_img(img_to_upload);
        question.setQuestion_chapter(question_chapter);
        question.setQuestion_ori(question_ori);
        question.setQuestion_option(option_to_upload);
        question.setQuestion_video(video_to_upload);

        questionService.insertQuestion(question);
        HashMap<String,Object> map=new HashMap<>();
        map.put("str_content",content_to_upload);
        map.put("str_option",option_to_upload);
        return map;
    }

    @RequestMapping("/question_table_edit.do")
    @ResponseBody
    public Map<String, Object> doQuestion_table_edit(int question_id, String question_content, String question_option, String question_answer,
                                                     String question_class,String question_chapter,String question_ori,String question_video,
                                                     @RequestParam(value="file_content",required = false) MultipartFile file_content,
                                                     @RequestParam(value="file_option",required = false) MultipartFile file_option,
                                                     @RequestParam(value="file_video",required = false) MultipartFile file_video,
                                                     HttpSession session) throws JsonProcessingException {
        String content_to_upload="";
        String option_to_upload="";
        String video_to_upload="";
        if(file_content==null){
            content_to_upload=question_content;
        }else{
            if(!file_content.isEmpty()){
                try {
                    InputStream in = file_content.getInputStream();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
                    int a = 0;
                    while((a = bufferedReader.read())!=-1){
                        char ch=(char)a;
                        content_to_upload+=ch;
                    }
                    in.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

        if(file_option==null){
            option_to_upload=question_option;
        }else{
            if(!file_option.isEmpty()){
                try {
                    InputStream in = file_option.getInputStream();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
                    int a = 0;
                    while((a = bufferedReader.read())!=-1){
                        char ch=(char)a;
                        option_to_upload+=ch;
                    }
                    in.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

        if(file_video==null){
            video_to_upload=question_video;
        }else{
            video_to_upload= UUID.randomUUID()+"_with_"+file_video.getOriginalFilename();
            String path= (String) session.getAttribute("img_save_path");
            path+="/question_img/";
            File file_tool=new File(path+question_video);
            if(!file_video.isEmpty()){
                try {
                    file_tool.delete();
                    File uploadFile=new File(path+video_to_upload);
                    Streams.copy(file_video.getInputStream(),new FileOutputStream(uploadFile.getAbsolutePath()),true);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

        Question question=new Question();
        question.setQuestion_id(question_id);
        question.setQuestion_content(content_to_upload);
        question.setQuestion_option(option_to_upload);
        question.setQuestion_answer(question_answer);
        question.setQuestion_class(question_class);
        question.setQuestion_chapter(question_chapter);
        question.setQuestion_ori(question_ori);
        question.setQuestion_video(video_to_upload);

        questionService.updateQuestionByQuestion_id(question);
        HashMap<String,Object> map=new HashMap<>();
        map.put("str_content",content_to_upload);
        map.put("str_option",option_to_upload);
        map.put("str_video",video_to_upload);
        return map;
    }

    @RequestMapping("/question_table_edit_init.do")
    @ResponseBody
    public Question doQuestion_table_edit_init(int question_id){
        return questionService.selectQuestionByQuestion_id(question_id);
    }

    @RequestMapping("/question_table_edit_upload_img.do")
    @ResponseBody
    public String doQuestion_table_edit_upload_img(@RequestParam(value="file",required = false) MultipartFile file_img,
                                               HttpSession session, int question_id) throws JsonProcessingException {
        Map<String,Object> map=new HashMap<>();
        if(session.getAttribute("flag_manager")!=null) {
            String img_to_upload = "";
            img_to_upload = UUID.randomUUID() + "_with_" + file_img.getOriginalFilename();
            String path = (String) session.getAttribute("img_save_path");
            path += "/question_img/";
            String question_img = questionService.selectQuestionByQuestion_id(question_id).getQuestion_img();
            if (file_img != null) {
                if (!file_img.isEmpty()) {
                    File file = new File(path + question_img);
                    file.delete();
                    try {

                        File uploadFile = new File(path + img_to_upload);
                        Streams.copy(file_img.getInputStream(), new FileOutputStream(uploadFile.getAbsolutePath()), true);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    questionService.updateQuestion_imgByQuestion_id(img_to_upload, question_id);
                }

            }
            map.put("code", 0);
            map.put("msg", "");
            map.put("data", img_to_upload);
        }else{
            map.put("code", 0);
            map.put("msg", "");
            map.put("data", "fail");
        }
        return new ObjectMapper().writeValueAsString(map);
    }

    @RequestMapping("/question_table_file_add.do")
    @ResponseBody
    public void doQuestion_table_file_add(@RequestParam(value = "file_content",required = false)MultipartFile file_content,
                                         String question_ori,String question_class,HttpSession session){
        String path= (String) session.getAttribute("img_save_path");
        path+="question_img/";
        if(question_class.equals("科一")){
            addKe1(path,file_content,question_ori,question_class);
        }else{
            addKe4(path,file_content,question_ori,question_class);
        }
    }


    public void addKe1(String path,MultipartFile file_content,String question_ori,String question_class){
        try {
            jxl.Workbook wb = null;
            wb = Workbook.getWorkbook(file_content.getInputStream());

            int sheetSize = wb.getNumberOfSheets();
            Sheet sheet = wb.getSheet(0);
            int row_total = sheet.getRows();

            FileOutputStream writer = null;
            int k = 0;
            int img_num = sheet.getNumberOfImages();
            for (int j = 1; j < row_total; j++) {

                Cell[] cells = sheet.getRow(j);
                Question question=new Question();
                question.setQuestion_video("");
                question.setQuestion_ori(question_ori);
                question.setQuestion_class(question_class);
                question.setQuestion_content(cells[0].getContents()+"、"+cells[1].getContents());
                if(!cells[2].getContents().equals(""))
                    question.setQuestion_img(cells[2].getContents()+".jpg");
                else
                    question.setQuestion_img("");
                String question_option="";
                String question_answer="";
                if(cells[8].getContents().equals("Y")||cells[8].getContents().equals("N")){
                    question_option="A、正确"+"\n"+"B、错误";
                    if(cells[8].getContents().equals("Y"))
                        question_answer="A";
                    else
                        question_answer="B";
                }else{
                    question_option+="A、"+cells[4].getContents()+"\n"
                            +"B、"+cells[5].getContents()+"\n"
                            +"C、"+cells[6].getContents()+"\n"
                            +"D、"+cells[7].getContents();
                    question_answer=cells[8].getContents();
                }
                question.setQuestion_option(question_option);
                question.setQuestion_answer(question_answer);

                String question_chapter=addNum(cells[9].getContents());
                question.setQuestion_chapter(question_chapter);
                questionService.insertQuestion(question);


                //将图片存入相应的路径
                if ((!"".equals(cells[2].getContents())) && k < img_num) {
                    writer = new FileOutputStream(path + cells[2].getContents() + ".jpg");
                    writer.write(sheet.getDrawing(k).getImageData());
                    k++;
                }


            }
            writer.close();

        }catch (Exception e){

        }
    }

    public void addKe4(String path,MultipartFile file_content,String question_ori,String question_class){
        try {
            jxl.Workbook wb = null;
            wb = Workbook.getWorkbook(file_content.getInputStream());

            int sheetSize = wb.getNumberOfSheets();
            Sheet sheet = wb.getSheet(0);
            int row_total = sheet.getRows();
            for(int i=1;i<row_total;i++){
                Cell[] cells=sheet.getRow(i);
                Question question=new Question();
                question.setQuestion_class(question_class);
                question.setQuestion_ori(question_ori);
                question.setQuestion_content(cells[0].getContents()+"、"+cells[1].getContents());

                int num=Integer.parseInt(cells[0].getContents());
                question.setQuestion_chapter(chooseChapter(num));

                String question_answer=cells[2].getContents();
                if(question_answer.equals("对"))
                    question_answer="A";
                if(question_answer.equals("错"))
                    question_answer="B";
                question.setQuestion_answer(question_answer);

                String question_option="";
                if(!cells[5].getContents().equals("")&&!cells[6].getContents().equals("")) {
                   question_option = "A、" + cells[3].getContents() + "\n"
                            + "B、" + cells[4].getContents() + "\n"
                            + "C、" + cells[5].getContents() + "\n"
                            + "D、" + cells[6].getContents();
                }else{
                    question_option = "A、" + cells[3].getContents() + "\n"
                            + "B、" + cells[4].getContents();
                }
                question.setQuestion_option(question_option);

                String url_str=cells[7].getContents();
                String question_img="";
                String question_video="";
                if(url_str.indexOf(".jpg")!=-1||url_str.indexOf(".png")!=-1) {
                    String picture_name = "ke4_picture" + i+".jpg";
                    question_img=picture_name;
                    downloadPicture(url_str,path,picture_name);
                }
                question.setQuestion_img(question_img);
                question.setQuestion_video(question_video);

                questionService.insertQuestion(question);

            }


        }catch (Exception e){
            e.printStackTrace();
        }
    }



    public String chooseChapter(int num){
        String res="";
        if(num>=1&&num<=22){
            res="1、违法行为综合判断与案例分析";
        }else{
            if(num<=156){
                res="2、安全行车常识";
            }else{
                if(num<=701){
                    res="3、常见交通标志、标线和交通手势辨识";
                }else{
                    if(num<=839){
                        res="4、驾驶职业道德和文明驾驶常识";
                    }else{
                        if(num<1181){
                            res="5、恶劣气候和复杂道路条件下驾驶常识";
                        }else{
                            res="6、紧急情况下避险常识";
                        }
                    }
                }
            }
        }
        return res;
    }


    public String addNum(String s){
        String res="";
        if(s.equals("道路交通安全法律、法规和规章")){
            res="1、"+s;
        }
        if(s.equals("交通信号")){
            res="2、"+s;
        }
        if(s.equals("安全行车、文明驾驶基础知识")){
            res="3、"+s;
        }
        if(s.equals("机动车驾驶操作相关基础知识")){
            res="4、"+s;
        }
        if(s.equals("交通事故救护常识")){
            res="5、"+s;
        }
        return res;
    }

    public  void downloadPicture(String urlString,String save_path,String filename) throws IOException {
        URL url = new URL(urlString);
        // 打开连接
        URLConnection con = url.openConnection();
        // 输入流
        InputStream is = con.getInputStream();
        // 1K的数据缓冲
        File file = new File(save_path+filename);
        FileOutputStream os = new FileOutputStream(file, true);
        Streams.copy(is,os,true);
    }
}
